package com.bolt.auth.security.admin.biz.sys.controller;


import com.bolt.auth.admin.api.sys.dto.RoleDTO;
import com.bolt.auth.admin.api.sys.dto.RoleQueryCriteria;
import com.bolt.auth.admin.api.sys.dto.converter.RoleConverter;
import com.bolt.auth.admin.api.sys.entity.DictDetailEntity;
import com.bolt.auth.admin.api.sys.entity.RoleEntity;
import com.bolt.auth.security.admin.biz.sys.service.RoleService;
import com.bolt.common.BoltConstants;
import com.bolt.common.utils.StrUtil;
import com.bolt.convention.data.PageInfo;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.support.spring.jpa.filter.FilterBuilder;
import com.bolt.support.spring.jpa.specification.QueryHelp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@RestController
@Api(tags = "角色管理")
@RequestMapping("/api/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation("查询角色")
    @GetMapping
    public ResultMessage page(Pageable pageable, RoleQueryCriteria roleQueryCriteria) {
        PageInfo<RoleEntity> pageInfo = roleService.findPage(pageable,
                (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, roleQueryCriteria, criteriaBuilder));
        return Results.success(pageInfo.map(K -> RoleConverter.toDTO(K)));
    }

    /**
     * 查找所有角色ID与名称
     *
     * @return
     */
    @ApiOperation("查找所有角色ID与名称")
    @GetMapping(value = "/all")
    public ResultMessage getAllRole() {
        List <RoleDTO> data = roleService.getAllRoleData();
        return Results.success(data);
    }

    @PostMapping
    @ApiOperation(notes = "角色信息新增操作", httpMethod = "POST", value = "角色信息新增操作")
    public ResultMessage create(@Validated @RequestBody RoleDTO roleDTO) {
        RoleEntity entity = RoleConverter.toEntity(roleDTO);
        if (StrUtil.isEmpty(entity.getCode()) || entity.getCode().length() < 6) {
            return Results.error("500", "角色编码不能未空且长度必须大于6小于 64。");
        }
        List <RoleEntity> roleList = roleService.findAll(new FilterBuilder<RoleEntity>()
                .lambda().eq(RoleEntity::getCode, entity.getCode()).build());
        if (roleList.size() > 0) {
            return Results.error("500", "角色编码【" + entity.getCode() + "】已存在！");
        }
        RoleEntity role = roleService.save(entity);
        return Results.success(role);
    }

    @PutMapping
    @ApiOperation(notes = "角色信息编辑操作", httpMethod = "PUT", value = "角色信息编辑操作")
    public ResultMessage<Void> update(@Validated(DictDetailEntity.Update.class) @RequestBody RoleDTO roleDTO) {
        RoleEntity entity = RoleConverter.toEntity(roleDTO);
        Optional <RoleEntity> optional = roleService.findOne(entity.getId());
        RoleEntity roleOld;
        if (!optional.isPresent()) {
            return Results.error("500", "查询记录的出错！");
        } else {
            roleOld = optional.get();
        }
        if (!roleOld.getCode().equals(entity.getCode())) {
            return Results.error("500", "原角色编码【" + roleOld.getCode() + "】不能修改为【" + entity.getCode() + "】！");
        }
        roleService.save(entity);
        return Results.success();
    }

    /**
     * 角色信息删除操作
     *
     * @param ids 菜单ID
     * @return
     */
    @DeleteMapping
    @ApiOperation(notes = "角色信息删除操作", httpMethod = "POST", value = "角色信息删除操作")
    public ResultMessage doDelete(@RequestBody Set <String> ids) {
        for (String id : ids) {
            if (StrUtil.isNotEmpty(id)) {
                Optional <RoleEntity> optional = roleService.findOne(id);
                RoleEntity role;
                if (!optional.isPresent()) {
                    return Results.error("500", "查询删除记录的id出错！");
                } else {
                    role = optional.get();
                }
                if (BoltConstants.ROLE_SUPER_USER.equals(role.getCode())) {
                    return Results.error("500", "角色【ROLE_SUPER_USER】不能删除！");
                }
                String users = roleService.getUserNamesByRoleId(role.getId());
                if (!"0".equals(users)) {
                    return Results.error("500", "用户【" + users + "】分配有该角色，不能删除！");
                }
                roleService.delete(role);

            } else {
                return Results.error("500", "删除记录的id不能为空！");
            }
        }
        return Results.success();
    }

    @ApiOperation("查找所有角色ID与名称")
    @GetMapping(value = "/getRolePrivilege/{roleId}")
    public ResultMessage getRolePrivilege(@PathVariable String roleId) {
        return Results.success(roleService.findPrivileges(roleId));
    }


    /**
     * 分配角色权限资源
     * @return
     */
    @PostMapping("/privileges")
    @ApiOperation(notes = "分配角色权限资源", httpMethod = "POST", value = "分配角色权限资源")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roleId", dataType = "String", required = true, value = "角色ID"),
            @ApiImplicitParam(paramType = "query", name = "privilegeIds", dataType = "String", required = true, value = "所选菜单ID，多个逗号隔开")
    })
    public ResultMessage<Void> privilegeR2sSave(
            @RequestParam(value = "roleId", required = true)
                    String roleId,
            @RequestParam(value = "privilegeIds", required = false)
                    String[] privilegeIds) {
        roleService.updateRelatedPrivilege(roleId, privilegeIds);
        return Results.success();
    }
}

 